<template>
	<div class="global-popupSelect-container">
		<div
			v-if="showInput"
			class="el-select"
			@click="openDialog"
		>
			<Input
				v-model="innerValue"
				:placeholder="placeholder"
				:class="{ 'link-style': disabled && innerValue }"
				readonly
				:validate-event="false"
				@mouseenter.native="inputHovering = true"
				@mouseleave.native="inputHovering = false"
			>
				<template #suffix>
					<i
						v-show="!showClose"
						:class="['el-select__caret', 'Input__icon', 'el-icon-arrow-up']"
					/>
					<i
						v-if="showClose"
						class="el-select__caret Input__icon el-icon-circle-close"
						@click.stop="clear"
					/>
				</template>
			</Input>
		</div>
		<template v-if="popupType === 'dialog'">
			<Dialog
				v-if="visible"
				:visible.sync="visible"
				:title="popupTitle"
				:close-on-click-modal="false"
				class="global-dialog global-dialog_center"
				lock-scroll
				:append-to-body="true"
				:width="popupWidth"
			>
				<Row
					v-if="innerFormSearchOptions.length>0"
					class="global-common-search-box"
					:gutter="16"
				>
					<Form>
						<Col
							v-for="item,index in innerFormSearchOptions"
							:key="index"
							:span="12"
						>
							<FormItem
								:label="item.config.label"
							>
								<!-- TODO 待引入组件 -->
								<component
									:is="item.config.tag"
									v-model="item.value"
									v-bind="item"
								/>
							</FormItem>
						</Col>
					</Form>
					<div class="head-search">
						<Button
							type="primary"
							icon="el-icon-search"
							@click="search()"
						>
							查询
						</Button>
						<Button
							icon="el-icon-refresh-right"
							@click="reset()"
						>
							重置
						</Button>
					</div>
				</Row>
				<McTable
					v-if="columnOptions.length"
					v-loading="listLoading"
					:data="list"
					:border="false"
					highlight-current-row
					:has-n-o="false"
					@row-click="rowClick"
				>
					<TableColumn width="35">
						<template #default="scope">
							<Radio
								v-model="checked"
								:label="scope.row.id"
							>
							&nbsp;
							</Radio>
						</template>
					</TableColumn>
					<TableColumn
						v-for="(item, i) in columnOptions"
						:key="i"
						:prop="item.value"
						:label="item.label"
					/>
				</McTable>
				<Empty
					v-else
					description="未配置列表字段"
				/>
				<pagination
					v-if="hasPage"
					:page="listQuery.currentPage"
					:limit="listQuery.pageSize"
					:total="total"
					@pagination="initData"
				/>
				<template #footer>
					<span
						class="dialog-footer"
					>
						<Button
							size="small"
							@click="visible = false"
						>取消</Button>
						<Button
							type="primary"
							size="small"
							@click="select"
						>确定</Button>
					</span>
				</template>
			</Dialog>
		</template>
		<template v-if="popupType === 'drawer'">
			<Drawer
				ref="drawer"
				:visible.sync="visible"
				:title="popupTitle"
				:wrapper-closable="false"
				:size="popupWidth"
				:append-to-body="true"
				class="global-common-drawer"
			>
				<div class="global-flex-main">
					<Row
						class="global-common-search-box"
						:gutter="16"
					>
						<Form @submit.native.prevent>
							<Col :span="10">
								<FormItem label="关键词">
									<Input
										v-model="listQuery.keyword"
										placeholder="请输入关键词"
										clearable
										class="search-input"
										@keyup.enter.native="search()"
									/>
								</FormItem>
							</Col>
							<Col :span="8">
								<FormItem>
									<Button
										type="primary"
										icon="el-icon-search"
										@click="search()"
									>
										查询
									</Button>
									<Button
										icon="el-icon-refresh-right"
										@click="reset()"
									>
										重置
									</Button>
								</FormItem>
							</Col>
						</Form>
						<div class="global-common-search-box-right">
							<Tooltip
								effect="dark"
								content="刷新"
								placement="top"
							>
								<Link
									icon="icon-ym icon-ym-Refresh global-common-head-icon"
									:underline="false"
									@click="initData()"
								/>
							</Tooltip>
						</div>
					</Row>
					<McTable
						v-loading="listLoading"
						:data="list"
						:border="false"
						highlight-current-row
						:has-n-o="false"
						@row-click="rowClick"
					>
						<TableColumn width="35">
							<template #default="scope">
								<Radio
									v-model="checked"
									:label="scope.row.id"
								>
									&nbsp;
								</Radio>
							</template>
						</TableColumn>
						<TableColumn
							v-for="(item, i) in columnOptions"
							:key="i"
							:prop="item.value"
							:label="item.label"
						/>
					</McTable>
					<pagination
						v-if="hasPage"
						:page="listQuery.currentPage"
						:limit="listQuery.pageSize"
						:total="total"
						@pagination="initData"
					/>
					<div class="drawer-footer">
						<Button
							size="small"
							@click="visible = false"
						>
							取消
						</Button>
						<Button
							type="primary"
							size="small"
							@click="select"
						>
							确定
						</Button>
					</div>
				</div>
			</Drawer>
		</template>
		<Form v-if="detailVisible">
			<Detail
				v-if="detailVisible"
				ref="Detail"
				@close="detailVisible = false"
			/>
		</Form>
	</div>
</template>

<script>
// import { getFieldDataSelect, getDataChange, getConfigData } from "@/api/onlineDev/visualDev";
import Detail from './detail/index.vue';
import {magic} from '@lexmis/magic-ui/pc';
import {EventBus} from '../../utils';
import {Input, Dialog, Row, Col, Form, TableColumn, FormItem, Button, Radio, Empty, Drawer, Tooltip, Link} from 'element-ui';
import McTable from '../table';
import 'element-ui/lib/theme-chalk/dialog.css';
const relationData = {};
export default {
	name:'McRelationForm',
	components:{Detail,McTable, Input,TableColumn, Dialog, Row, Col, Form, FormItem, Button, Radio, Empty, Drawer, Tooltip},
	model:{
		prop:'value',
		event:'input',
	},
	props:{
		value:{
			type:null,
			default:null,
		},
		showInput:{
			type:Boolean,
			default:true,
		},
		config:{
			type:Object,
			default: () => {},
		},
		placeholder:{
			type:String,
			default:'请选择',
		},
		relationField:{
			type:String,
			default:'',
		},
		field:{
			type:String,
			default:'',
		},
		columnOptions:{
			type:Array,
			default: () => [],
		},
		drawingList:{
			type:Array,
			default: () => [],
		},
		formRule:{
			type:Object,
			default: () => {},
		},
		formSearchOptions:{
			type:Array,
			default: () => [],
		},
		hasPage:{
			type:Boolean,
			default:false,
		},
		pageSize:{
			type:Number,
			default:20,
		},
		disabled:{
			type:Boolean,
			default:false,
		},
		multiple:{
			type:Boolean,
			default:false,
		},
		clearable:{
			type:Boolean,
			default:true,
		},
		popupType:{
			type:String,
			default:'dialog',
		},
		popupTitle:{
			type:String,
			default:'选择数据',
		},
		popupWidth:{
			type:String,
			default:'800px',
		},
		showField:{
			type:String,
			default:'',
		},
	},
	data(){
		return {
			list:[],
			innerValue:null,
			listQuery:{
				keyword:'',
				currentPage:1,
				pageSize:20,
			},
			total:0,
			checked:'',
			checkedTxt:'',
			checkedRow:{},
			listLoading:false,
			inputHovering:false,
			visible:false,
			detailVisible:false,
			innerFormSearchOptions:[],
			formDataFields:[],
		};
	},
	computed:{
		showClose(){
			const hasValue = this.multiple
				? Array.isArray(this.value) && this.value.length > 0
				: this.value !== undefined && this.value !== null && this.value !== '';
			const criteria = this.clearable && !this.disabled && this.inputHovering && hasValue;
			return criteria;
		},
	},
	watch:{
		value(){
			this.setDefault(true);
		},
		'config.dataTypeId'(newId){
			this.getTemplateInfo(newId);
		},
		formSearchOptions:{
			deep:true,
			handler(newVal){
				this.buildFormSearchOptions(newVal);
			},
		},
	},
	created(){
		this.listQuery.pageSize = this.hasPage ? this.pageSize : 10000;
		this.config?.dataTypeId ? this.getTemplateInfo(this.config.dataTypeId) : null;
		if(this.value === ''){
			this.innerValue = null;
			this.$emit('input', null);
		}
		this.initData();
	},
	methods:{
		getTemplateInfo(id){
			if(!id) return;
			magic.core
				.service({
					url:`/api/form/instance/config`,
					method:'get',
					params:{templateId:id},
				})
				.then(({data}) => {
					this.formDataFields = data.formData.fields;
					this.buildFormSearchOptions(this.formSearchOptions);
				});
		},
		buildFormSearchOptions(options){
			const formDataFieldsMap = new Map(this.formDataFields.map((item) => [item.model, item]));
			this.innerFormSearchOptions = options
				.filter((item) => formDataFieldsMap.has(item.model))
				.map((item) => {
					const {slot, ...rest} = formDataFieldsMap.get(item.model);
					return {
						...rest,
						...item,
						value:'',
					};
				});
		},
		initData(){
			if(!this.config.dataTypeId) return;
			this.listLoading = true;
			magic.core
				.service({
					url:'/api/form/instance/list-select',
					method:'post',
					data:{
						templateId:this.config.dataTypeId,
						query:{
							matchLogic:'AND',
							condition:this.innerFormSearchOptions.filter((item) => item.value).map((item) => ({
								model:item.model,
								value:[item.value],
								symbol:item.symbol,
							})),
						},
						currentPage:this.listQuery.currentPage,
						pageSize:this.listQuery.pageSize,
						columnOptions:this.columnOptions.map((o) => o.value),
						formRule:this.formRule,
					},
				}).then((res) => {
					this.list = res.data.list;
					this.total = res.data.total;
					this.listLoading = false;
					this.setDefault(false);
				});
            // getFieldDataSelect(this.config.dataTypeId, query)
            //     .then(res => {
            //         this.list = res.data.list;
            //         this.total = res.data.pagination.total;
            //         this.listLoading = false;
            //         this.setDefault();
            //     })
            //     .catch(() => {
            //         this.listLoading = false;
            //     });
		},
		search(){
			this.listQuery.currentPage = 1;
			this.listQuery.pageSize = this.hasPage ? this.pageSize : 10000;
			this.initData();
		},
		reset(){
			this.listQuery.keyword = '';
			this.listQuery.currentPage = 1;
			this.listQuery.pageSize = this.hasPage ? this.pageSize : 10000;
			this.innerFormSearchOptions = this.innerFormSearchOptions.map((item) => ({
				...item,
				value:'',
			}));
			this.initData();
		},
		openDialog(){
			if(this.disabled){
				if(!this.value) return;
                // getConfigData(this.config.dataTypeId).then(res => {
                //     if (!res.data) return;
                //     if (!res.data.formData) return;
                //     const formData = JSON.parse(res.data.formData);
                //     formData.popupType = "general";
                //     this.detailVisible = true;
                //     this.$nextTick(() => {
                //         this.$refs.Detail.init(formData, this.config.dataTypeId, this.value);
                //     });
                // });
				return;
			}
			this.checked = this.value;
			this.visible = true;
			this.reset();
		},
		clear(){
			this.checked = '';
			this.innerValue = null;
			this.checkedRow = {};
			this.$emit('input', this.checked);
			this.$emit('change', this.checked, this.checkedRow);
		},
		select(){
			console.log(this.checked, '选择的1111');
			console.log(this.checkedRow, '选择的2222');

			if(!this.checked) return;
			this.$emit('input', this.checked);
			this.$emit('change', this.checked, this.checkedRow);
			this.visible = false;
		},
		rowClick(row){
			this.checked = row.id;
			this.checkedTxt = row[this.relationField];
			this.checkedRow = row;
		},
		setDefault(updated = true){
			this.getItemValue(this.value, updated);
		},
		getItemValue(val, updated = true){
			if(val){
				if(!this.config.dataTypeId) return;
				magic.core.service({
					url:'/api/form/instance/data',
					method:'get',
					params:{
						templateId:this.config.dataTypeId,
						id:val,
					},
				}).then(({data}) => {
					this.innerValue = data.data[this.relationField];
					this.checkedTxt = data.data[this.relationField];
					relationData[this.field] = data;
					if(updated){
						EventBus.$emit('trigger-relation-formattr', relationData);
					}
				});
			}else{
				this.innerValue = null;
				this.checkedTxt = '';
				if(!this.field) return;
			}
		},
	},
};
</script>
<style lang="scss" scoped>
::v-deep.Dialog__body {
    height: 70vh;
    padding: 0 0 10px !important;
    display: flex;
    flex-direction: column;
    overflow: hidden;

    .global-common-search-box {
        margin-bottom: 0;

        .global-common-search-box-right {
            padding: 10px 10px 0 0;
        }
    }
}

.link-style {
    ::v-deep.Input__inner {
        color: #1890ff !important;
        text-decoration: underline;
        cursor: pointer !important;
    }
}
.head-search{
	text-align: right;
	margin-bottom: 10px;
}
</style>